import json

from django.shortcuts import render,redirect
from django.urls import reverse
from system.models import User,Goods,Unit,GoodsType,Pic

import socket    #获取ip地址用

#接口
from django.http import HttpResponse,JsonResponse
from django.views.decorators.csrf import csrf_exempt

from system.views import SUCCESS_CODE,ERR_CODE,ERR_TIMEOUT,SUCCESS_MESSAGE,ERR_MESSAGE


# 添加商品
@csrf_exempt
def addGoods(request):
    dic = {}
    if request.method == "POST":
        name = request.POST.get('name')
        price = request.POST.get('price')
        type = int(request.POST.get('type'))
        preferential = request.POST.get('preferential')
        if preferential == 'false':
            preferential = False
        elif preferential == 'true':
            preferential = True
        sum = request.POST.get('sum')
        # soldSum = request.POST.get('soldSum')
        unitId = int(request.POST.get('unit'))
        try:
            picture = int(request.POST.get('picture'))
        except:
            print('获取不到picture')
            picture = 2
        goods = Goods.objects.filter(name=name)
        if goods:
            dic['code'] = ERR_CODE
            dic['message'] = '该商品已存在'
        else:
            newGoods = Goods()
            newGoods.name = name
            newGoods.price = price
            newGoods.type = GoodsType.objects.filter(id=type)[0]
            newGoods.sum = sum
            newGoods.unitId = Unit.objects.filter(id=unitId)[0]
            newGoods.soldSum = 0
            newGoods.preferential = preferential
            newGoods.picture = Pic.objects.filter(id=picture)[0]
            if preferential:
                preferentialPrice = request.POST.get('preferentialPrice')
                newGoods.preferentialPrice = preferentialPrice
            else:
                newGoods.preferentialPrice = price
            newGoods.save()

            dic['code'] = SUCCESS_CODE
            dic['message'] = '添加成功'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})

"""获取商品数据"""
@csrf_exempt
def getGoodsData(request):
    dic = {}
    if request.method == "POST":
        typeId = int(request.POST.get('typeId'))
        if typeId == -1:
            info = Goods.objects.all()
        else:
            info = Goods.objects.filter(type_id=typeId)
        if info:
            goodsList = []
            for i in info:
                data = {
                    'id': i.id,
                    'name': i.name,
                    'price': i.price,
                    'type': i.type.name,
                    'preferential': i.preferential,
                    'preferentialPrice': i.preferentialPrice,
                    'sum': i.sum,
                    'soldSum': i.soldSum,
                    'unitId': i.unitId.name,
                    'picture': i.picture.file.url,
                    'isShelves': i.isShelves
                }
                goodsList.append(data)

            pageSize = int(request.POST.get('pageSize'))
            page = int(request.POST.get('pageId'))
            minSize = (page - 1) * pageSize
            maxSize = page * pageSize

            if maxSize >= len(goodsList):
                dic['data'] = {
                    'goodsList': goodsList[minSize:],
                    'size': len(goodsList)
                }
            else:
                dic['data'] = {
                    'goodsList': goodsList[minSize: maxSize],
                    'size': len(goodsList)
                }

            dic['code'] = SUCCESS_CODE
            dic['message'] = SUCCESS_MESSAGE
        else:
            dic['data'] = {
                'goodsList': [],
                'size': 0
            }
            dic['code'] = SUCCESS_CODE
            dic['message'] = '暂时没有商品'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})

"""查询单个商品"""
@csrf_exempt
def getGoods(request):
    dic ={}
    if request.method == "POST":
        id = request.POST.get('id')
        goods = Goods.objects.filter(id=id)
        if goods:
            data = {
                'id': goods[0].id,
                'name': goods[0].name,
                'price': goods[0].price,
                'type': goods[0].type.id,
                'preferential': goods[0].preferential,
                'preferentialPrice': goods[0].preferentialPrice,
                'sum': goods[0].sum,
                'soldSum': goods[0].soldSum,
                'unit': goods[0].unitId.id,
                'file': {
                    'id': goods[0].picture.id,
                    'name': goods[0].picture.name,
                },
                'isShelves': goods[0].isShelves
            }
            dic['data'] = data
            dic['code'] = SUCCESS_CODE
            dic['message'] = SUCCESS_MESSAGE
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '没有该商品'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})

"""修改商品是否上架"""
@csrf_exempt
def changeGoodsShelves(request):
    dic = {}
    if request.method == 'POST':
        id = request.POST.get('id')
        goods = Goods.objects.filter(id=id)
        if goods:
            if goods[0].isShelves:
                goods[0].isShelves = False
            else:
                goods[0].isShelves = True
            goods[0].save()
            dic['code'] = SUCCESS_CODE
            dic['message'] = SUCCESS_MESSAGE
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '没有该商品'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})

"""删除商品"""
@csrf_exempt
def deleteGoods(requset):
    dic = {}
    if requset.method == 'POST':
        id = requset.POST.get('id')
        goods = Goods.objects.filter(id=id)
        if goods:
            if goods[0].picture.name != '暂无图片':
                goods[0].picture.delete()
            goods[0].delete()
            dic['code'] = SUCCESS_CODE
            dic['message'] = SUCCESS_MESSAGE
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '该商品不存在'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})

"""修改商品数据"""
@csrf_exempt
def editGoods(request):
    dic = {}
    if request.method == 'POST':
        id = request.POST.get('id')
        goods = Goods.objects.filter(id=id)
        if goods:
            goods = goods[0]
            goods.name = request.POST.get('name')
            goods.price = request.POST.get('price')
            goods.type = GoodsType.objects.filter(id=int(request.POST.get('type')))[0]
            preferential = request.POST.get('preferential')
            if preferential == 'false':
                goods.preferential = False
            elif preferential == 'true':
                goods.preferential = True
            else:
                goods.preferential = False
            if goods.preferential:
                goods.preferentialPrice = request.POST.get('preferentialPrice')
            else:
                goods.preferentialPrice = request.POST.get('price')
            goods.sum = request.POST.get('sum')
            goods.soldSum = request.POST.get('soldSum')
            goods.unitId = Unit.objects.filter(id=int(request.POST.get('unit')))[0]
            goods.picture = Pic.objects.filter(id=int(request.POST.get('picture')))[0]
            goods.save()

            dic['code'] = SUCCESS_CODE
            dic['message'] = SUCCESS_MESSAGE
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '没有该商品'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})

"""验证图片上传"""
@csrf_exempt
def upPic(request):
    dic = {}
    pic = request.FILES.get('pic')
    if pic != None:
        newPic = Pic()
        newPic.name = pic.name
        newPic.file = pic
        newPic.save()
        id = Pic.objects.filter(name=pic.name)[0].id
        dic['code'] = SUCCESS_CODE
        dic['message'] = SUCCESS_MESSAGE
        dic['pic'] = {
            'id': id,
            'name': pic.name,
        }
    else:
        dic['code'] = ERR_CODE
        dic['message'] = '没有上传图片'
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})

"""获取select用的商品"""
@csrf_exempt
def getGoodsOfSelect(request):
    dic = {}
    if request.method == 'POST':
        goods = Goods.objects.all()
        if goods:
            data = []
            for i in goods:
                data.append({'name':i.name, 'id': i.id})
            dic['code'] = SUCCESS_CODE
            dic['message'] = SUCCESS_MESSAGE
            dic['data'] = data
        else:
            dic['code'] = ERR_CODE
            dic['message'] = '暂时没有商品'
    else:
        dic['code'] = ERR_CODE
        dic['message'] = ERR_MESSAGE
    return JsonResponse(dic, json_dumps_params={'ensure_ascii': False})